<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <!-- <ElFormItem label="头像" prop="avatar">
        <ImageSelector v-model="formData.image" :multiple="false" />
      </ElFormItem> -->
      <!-- <ElFormItem label="图片集" prop="images">
        <ImageSelector v-model="formData.images" :multiple="true" />
      </ElFormItem> -->
      <ElFormItem label="类型名称" prop="name">
        <ElInput v-model="formData.name" placeholder="请输入类型名称" />
      </ElFormItem>
      <!-- <ElFormItem label="状态" prop="status">
        <ElSelect v-model="formData.status">
          <ElOption label="正常" value="1" />
          <ElOption label="冻结" value="0" />
        </ElSelect>
      </ElFormItem> -->
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { addResourceApi, editResourceApi } from '@/api/common'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<any>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: '', // 新增 id 字段，解决类型错误
    name: ''
  })

  // 表单验证规则
  const rules: FormRules = {
    name: [
      { required: true, message: '请输入类型名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
    // password: [
    //   { required: true, message: '请输入密码', trigger: 'blur' },
    //   { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    // ],
    // status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
    // role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData
    if (isEdit && row) {
      Object.assign(formData, {
        id: isEdit && row ? row.id || '' : '',
        name: isEdit && row ? row.name || '' : ''
      })
    } else {
      Object.assign(formData, {
        id: '',
        name: ''
      })
    }
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后触发提交事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        let submitData: any = { ...formData }
        if (dialogType.value === 'edit') {
          submitData = { ...submitData, id: formData.id }
        } else {
          // 添加时不传 id 字段
          delete submitData.id
        }
        if (dialogType.value === 'add') {
          await addResourceApi(submitData)
          ElMessage.success('添加成功')
        } else {
          await editResourceApi(submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        emit('submit') // 父组件监听 submit 事件后刷新列表
      }
    })
  }
</script>
